package hu.issue.framework.web.servlet;

import hu.issue.framework.web.controller.Controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ControllerInvokerServlet extends HttpServlet {
	private static final long serialVersionUID = -5327554353984785681L;

	@Override
	protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		final ControllerMapper mapper = ContextUtil.getControllerMapper(getServletContext());
		final ControllerRegistry registry = ContextUtil.getControllerRegistry(getServletContext());
		final String controllerName = mapper.map(request);
		final Controller controller = registry.getController(controllerName);
		if (controller == null) {
			response.setStatus(404);
			return;
		}

		final ViewHandler handler = ContextUtil.getViewHandler(getServletContext());
		try {
			final String view = controller.handleRequest(request, response);
			handler.handleView(view, request, response);
		} catch (final Exception ex) {
			handler.handleException(ex, request, response);
			ex.printStackTrace();
		}
	}
}
